import { defineStore } from "pinia";
import { ref, computed } from "vue";
import Taro from "@tarojs/taro";
import { post } from "../utils/request";

declare const wx: any;

/**
 * 用户信息接口
 */
export interface UserInfo {
  level_id: number;
  type_merchant: string | null;
  imaccid: string;
  card_balance: number;
  real_status: number;
  imtoken: string;
  recommend_pic: string | null;
  user_type: string | null;
  balance: number | null;
  avatar_url: string | null;
  name: string | null;
  blocked_balances: number | null;
  deposit: number | null;
  id: number;
  recommend_code: string | null;
  vip: number;
  merchantType: string | null;
  openid: string | null;
  team_leader: number;
  promoter: number;
  is_receive: number; //是否可以领取任务 0 不能 1 能
  is_buy: number; //是0时 不能购买会员
}

/**
 * 用户 Store
 * 管理用户信息的状态和操作
 * 包含用户基本信息、VIP等级、余额、推广码等
 */
export const useUserStore = defineStore("user", () => {
  // 用户信息
  const userInfo = ref<UserInfo>({
    level_id: 0,
    type_merchant: null,
    imaccid: "",
    card_balance: 0,
    real_status: 0,
    imtoken: "",
    recommend_pic: null,
    user_type: null,
    balance: null,
    avatar_url: null,
    name: null,
    blocked_balances: null,
    deposit: null,
    id: 0,
    recommend_code: null,
    vip: 0,
    merchantType: null,
    openid: null,
    team_leader: 0,
    promoter: 0,
    is_receive: 0,
    is_buy: 0,
  });

  // 位置
  const locationObj = ref<any>({
    adInfo: null, // 地址信息
    address: null, // 地址详情
    location: {
      lat: null,
      lng: null,
    },
  });

  /**
   * 从缓存加载位置信息
   */
  const loadLocationFromCache = () => {
    try {
      const cachedLocation = Taro.getStorageSync("locationObj");
      if (cachedLocation) {
        locationObj.value = cachedLocation;
        console.log("从缓存加载位置信息:", locationObj.value);
      }
    } catch (error) {
      console.error("加载位置缓存失败:", error);
    }
  };

  /**
   * 保存位置信息到缓存
   */
  const saveLocationToCache = () => {
    try {
      Taro.setStorageSync("locationObj", locationObj.value);
      console.log("位置信息已保存到缓存:", locationObj.value);
    } catch (error) {
      console.error("保存位置缓存失败:", error);
    }
  };

  const wxObj = ref<any>({
    appId: null,
    nonceStr: null,
    signature: null,
    timestamp: null,
  });

  const DEBUG_LOG_STORAGE_KEY = "authDebugLogs";

  const appendDebugLog = (message: string) => {
    try {
      const cache: Array<{ timestamp: number; message: string }> = Taro.getStorageSync(DEBUG_LOG_STORAGE_KEY) || [];
      const nextCache = [...cache, { timestamp: Date.now(), message }];
      if (nextCache.length > 30) {
        nextCache.splice(0, nextCache.length - 30);
      }
      Taro.setStorageSync(DEBUG_LOG_STORAGE_KEY, nextCache);
    } catch (error) {
      console.error("写入调试日志失败:", error);
    }
  };

  // 初始化时从缓存加载位置信息
  loadLocationFromCache();

  const sdkInit = ref<boolean>(false);

  // 用户token
  const token = ref<string>("");

  // 是否已登录
  const isLoggedIn = computed(() => !!token.value);

  // 是否为VIP用户
  const isVipUser = computed(() => userInfo.value.vip > 0);

  // 用户余额（格式化显示）
  const formattedBalance = computed(() => {
    return userInfo.value.balance ? `¥${userInfo.value.balance.toFixed(2)}` : "¥0.00";
  });

  /**
   * 用户登录
   * @param loginData 登录数据
   */
  const login = async (loginData: { username: string; password: string }) => {
    try {
      // 这里应该调用实际的登录API
      // const response = await request.post('/api/login', loginData)

      // 模拟登录成功
      const mockUserInfo: UserInfo = {
        level_id: 1,
        type_merchant: null,
        imaccid: "",
        card_balance: 0,
        real_status: 1,
        imtoken: "",
        recommend_pic: null,
        user_type: "user",
        balance: 1580.5,
        avatar_url: "http://www.dzgktf.com/templets/default/images/wtyt.jpg",
        name: loginData.username,
        blocked_balances: null,
        deposit: null,
        id: 1,
        recommend_code: "ABC123456",
        vip: 2,
        merchantType: null,
        openid: null,
        team_leader: 0,
        promoter: 0,
        is_receive: 1,
        is_buy: 1,
      };

      const mockToken = "mock_token_" + Date.now();

      // 更新状态
      userInfo.value = mockUserInfo;
      token.value = mockToken;

      // 保存到本地存储
      Taro.setStorageSync("userInfo", mockUserInfo);
      Taro.setStorageSync("token", mockToken);

      return { success: true, message: "登录成功" };
    } catch (error) {
      console.error("登录失败:", error);
      return { success: false, message: "登录失败" };
    }
  };

  /**
   * 用户登出
   */
  const logout = () => {
    // 清空状态
    userInfo.value = {
      level_id: 0,
      type_merchant: null,
      imaccid: "",
      card_balance: 0,
      real_status: 0,
      imtoken: "",
      recommend_pic: null,
      user_type: null,
      balance: null,
      avatar_url: null,
      name: null,
      blocked_balances: null,
      deposit: null,
      id: 0,
      recommend_code: null,
      vip: 0,
      merchantType: null,
      openid: null,
      team_leader: 0,
      promoter: 0,
      is_receive: 0,
      is_buy: 0,
    };
    token.value = "";

    // 清除本地存储
    Taro.removeStorageSync("userInfo");
    Taro.removeStorageSync("token");

    // 跳转到登录页
    Taro.redirectTo({
      url: "/pages/webs/register",
    });
  };

  /**
   * 更新用户信息
   * @param newUserInfo 新的用户信息
   */
  const updateUserInfo = (newUserInfo: Partial<UserInfo>) => {
    userInfo.value = { ...userInfo.value, ...newUserInfo };

    // 更新本地存储
    Taro.setStorageSync("userInfo", userInfo.value);
  };

  /**
   * 更新用户余额
   * @param newBalance 新的余额
   */
  const updateBalance = (newBalance: number) => {
    userInfo.value.balance = newBalance;
    Taro.setStorageSync("userInfo", userInfo.value);
  };

  /**
   * 更新VIP等级
   * @param newVipLevel 新的VIP等级
   */
  const updateVipLevel = (newVipLevel: number) => {
    userInfo.value.vip = newVipLevel;
    Taro.setStorageSync("userInfo", userInfo.value);
  };

  /**
   * 从本地存储恢复用户信息
   */
  const restoreUserInfo = () => {
    try {
      const storedUserInfo = Taro.getStorageSync("userInfo");
      console.log("storedUserInfo", storedUserInfo);
      const storedToken = Taro.getStorageSync("token");
      console.log("storedToken", storedToken);
      if (storedUserInfo && storedToken) {
        userInfo.value = storedUserInfo;
        token.value = storedToken;
      }
    } catch (error) {
      console.error("恢复用户信息失败:", error);
    }
  };

  /**
   * 检查用户是否已登录
   */
  const checkLoginStatus = () => {
    if (!token.value) {
      Taro.redirectTo({
        url: "/pages/webs/register",
      });
      return false;
    }
    return true;
  };

  /**
   * 获取用户推广链接
   */
  const getPromotionLink = computed(() => {
    return `https://nengliguangchang.suchi.hongyutiancheng.com/register?recommend_code=${userInfo.value.recommend_code}`;
  });

  /**
   * 获取VIP等级显示文本
   */
  const getVipLevelText = computed(() => {
    const levelMap: Record<number, string> = {
      0: "普通用户",
      1: "VIP会员",
      2: "黄金VIP",
      3: "钻石VIP",
      4: "至尊VIP",
    };
    return levelMap[userInfo.value.vip] || "普通用户";
  });

  const fetchUserInfo = async () => {
    const res = await post("/my/index");
    console.log("res === info", res);
    if (res.code == 0) {
      userInfo.value = res.data.columns;
      console.log(userInfo.value);
      wxAuth();
      // getLocation()
    }
  };

  const wxAuth = async () => {
    if (sdkInit.value) {
      console.log("sdkInit.value", sdkInit.value);
      return;
    }
    //判断当前环境是否为开发环境，是否微信浏览器
    // console.log("Taro.getCurrentInstance().router", Taro.getCurrentInstance().router);
    const currentUrl = window.location.href.split("#")[0];
    appendDebugLog(`请求微信JSSDK签名: ${currentUrl}`);
    const res = await post("/weChat/JSSDK", {
      url: currentUrl,
    });
    console.log("res.data === wxAuth", res);
    wxObj.value = res.data;
    appendDebugLog("微信JSSDK签名请求成功");

    wx.config({
      debug: false,
      appId: wxObj.value.appId,
      timestamp: wxObj.value.timestamp,
      nonceStr: wxObj.value.nonceStr,
      signature: wxObj.value.signature,
      jsApiList: ["chooseWXPay", "openLocation", "getLocation", "updateAppMessageShareData", "updateTimelineShareData", "requestMerchantTransfer"],
    });

    wx.ready(function () {
      console.log("wx.ready 😊😊");
      appendDebugLog("微信JSSDK 初始化成功");
      // Taro.showToast({
      //   title: "微信JS-SDK初始化成功",
      //   icon: "success"
      // })

      // 获取当前位置
      if (!locationObj.value.address_component?.province) {
        getLocation("wx-sdk");
      }

      // 自定义"分享给朋友"
      wx.updateAppMessageShareData({
        title: "能力都市",
        desc: "让天下没有难找的收入",
        link: window.location.href,
        imgUrl: "https://www.h5.nl9555.com/share.jpg",
        success: function () {},
      });

      // 自定义"分享到朋友圈"
      wx.updateTimelineShareData({
        title: "能力都市",
        link: window.location.href,
        imgUrl: "https://www.h5.nl9555.com/share.jpg",
        success: function () {},
      });
    });

    // wx.ready(function() {
    //   console.log("wx.ready");
    //   Taro.showToast({
    //     title: "微信JS-SDK初始化成功",
    //     icon: "success"
    //   })
    // });

    wx.error(function (res: any) {
      console.log("wx.error", res);
      appendDebugLog(
        `微信JSSDK 初始化失败: ${JSON.stringify({
          errMsg: res?.errMsg,
          signature: wxObj.value?.signature,
          timestamp: wxObj.value?.timestamp,
          nonceStr: wxObj.value?.nonceStr,
          appId: wxObj.value?.appId,
        })}`
      );
      // Taro.showToast({
      //   title: "微信JS-SDK初始化失败",
      //   icon: "error"
      // })
    });
  };

  // 获取地址信息
  async function getAddressInfo(lat: any, lng: any, source: "wx-sdk" | "browser" | "ip" = "browser") {
    // 返回一个新的Promise对象
    return new Promise((resolve, reject) => {
      // 验证token是否存在
      const tokenStr = localStorage.getItem("token");
      if (!tokenStr) {
        reject(new Error("未找到token，请先登录"));
        return;
      }

      let tokenData: { data?: string };
      try {
        tokenData = JSON.parse(tokenStr);
        if (!tokenData.data) {
          throw new Error("token格式不正确");
        }
      } catch (error: unknown) {
        const message = error instanceof Error ? error.message : String(error);
        reject(new Error("解析token失败: " + message));
        return;
      }

      // 根据是否有经纬度选择不同的API地址
      const url =
        lat && lng
          ? `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=N4DBZ-Q2W37-JNHXL-PI6NN-55FH5-2BF74&get_poi=1`
          : `https://apis.map.qq.com/ws/location/v1/ip/?key=N4DBZ-Q2W37-JNHXL-PI6NN-55FH5-2BF74&get_poi=1&ip=192.168.1.14`;

      fetch("https://www.api.nl9555.com/index/proxyForwarding", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          token: tokenData.data,
        },
        body: JSON.stringify({ url: url }),
      })
        .then((res) => res.json())
        .then((res) => {
          if (res.statusCode !== 200) {
            throw new Error(res.data?.message || "请求失败，状态码不为200");
          }

          // 解析返回的body内容
          try {
            const result = JSON.parse(res.body);
            // 检查地图API返回的状态
            if (result.status !== 0) {
              throw new Error(result.message || "地图API返回错误");
            }
            console.log("位置信息==>", result.result);
            console.log("getAddressInfo 成功:", { source, result: result.result });
            resolve(result.result);
          } catch (parseError: unknown) {
            const message = parseError instanceof Error ? parseError.message : String(parseError);
            reject(new Error("解析返回数据失败: " + message));
          }
        })
        .catch((error) => {
          // 捕获所有异常并传递给reject
          reject(error);
        });
    });
  }

  // 获取当前位置
  async function getLocation(source: "wx-sdk" | "browser" = "browser"): Promise<void> {
    console.log("getLocation 调用:", { source });

    if (source === "wx-sdk") {
      const wxAvailable = typeof wx !== "undefined" && typeof wx.getLocation === "function";
      if (!wxAvailable) {
        console.log("wx-sdk 不可用，降级使用浏览器定位");
        return getLocation("browser");
      }

      return new Promise((resolve, reject) => {
        wx.getLocation({
          type: "gcj02",
          success: async (res: { latitude: number; longitude: number }) => {
            try {
              const result = await getAddressInfo(res.latitude, res.longitude, "wx-sdk");
              locationObj.value = result;
              saveLocationToCache();
              console.log("locationObj 更新完成:", { source: "wx-sdk", location: locationObj.value });
              resolve();
            } catch (error) {
              console.error("wx-sdk 地址解析失败:", error);
              locationObj.value = {
                location: {
                  lat: res.latitude,
                  lng: res.longitude,
                },
                address: "微信定位成功，解析失败，使用基础坐标",
                adInfo: null,
              };
              saveLocationToCache();
              console.log("locationObj 更新完成:", { source: "wx-sdk-fallback", location: locationObj.value });
              resolve();
            }
          },
          fail: (error: any) => {
            console.error("微信SDK 获取定位失败:", error);
            console.log("降级使用浏览器定位获取位置信息");
            getLocation("browser").then(resolve).catch(reject);
          },
        });
      });
    }

    return new Promise((resolve, reject) => {
      if (!navigator.geolocation) {
        const err = new Error("浏览器不支持地理位置获取");
        console.error("获取位置失败==>:", { source: "browser", error: err });
        reject(err);
        return;
      }

      navigator.geolocation.getCurrentPosition(
        async (position) => {
          const { latitude, longitude } = position.coords;
          try {
            const result = await getAddressInfo(latitude, longitude, "browser");
            locationObj.value = result;
            saveLocationToCache();
            console.log("locationObj 更新完成:", { source: "browser", location: locationObj.value });
            resolve();
          } catch (error) {
            console.error("浏览器定位解析失败:", error);
            locationObj.value = {
              location: {
                lat: latitude,
                lng: longitude,
              },
              address: "浏览器定位成功，解析失败，使用基础坐标",
              adInfo: null,
            };
            saveLocationToCache();
            console.log("locationObj 更新完成:", { source: "browser-fallback", location: locationObj.value });
            resolve();
          }
        },
        (error: GeolocationPositionError) => {
          console.error("获取位置失败==>:", { source: "browser", error });
          reject(error);
        }
      );
    });
  }

  async function checkIsReceive() {
    if (userInfo.value.is_receive == 1) {
      return true;
    }
    return new Promise<boolean>((resolve) => {
      Taro.showModal({
        title: "提示",
        content: "请先进行实名认证",
        confirmText: "去认证",
        cancelText: "取消",
        success: (res) => {
          if (res.confirm) {
            Taro.navigateTo({
              url: "/pages/registration/auth-person",
            });
          }
          resolve(false);
        },
        fail: () => {
          resolve(false);
        },
      });
    });
  }

  return {
    checkIsReceive,
    wxObj,
    locationObj,
    // 状态
    userInfo,
    token,
    isLoggedIn,
    isVipUser,
    formattedBalance,
    getPromotionLink,
    getVipLevelText,

    // 方法
    login,
    logout,
    updateUserInfo,
    updateBalance,
    updateVipLevel,
    restoreUserInfo,
    checkLoginStatus,
    fetchUserInfo,
    getAddressInfo,
    getLocation,
    // 位置缓存方法
    loadLocationFromCache,
    saveLocationToCache,
  };
});
